package com.example.yskjproject.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.yskjproject.R;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.CardMediaModel;
import com.example.yskjproject.model.CardModel;
import com.example.yskjproject.model.FollowModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.CashUtil;
import com.example.yskjproject.utils.LogUtils;
import com.example.yskjproject.utils.LoginDialogShowUtil;
import com.example.yskjproject.view.dialog.LoginWorkDialogHelper;
import com.example.yskjproject.view.dialog.WorkDialogHelper;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ContentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_NORMAL = 0;
    private static final int TYPE_FIRST = 1;

    private Context context;
    private List<CardModel> data;
    private FragmentActivity activity;
    private Gson gson = new Gson();
    private int mScreenWidth;
    private int mOriginalWidth;
    private int mOriginalHeight;

    public ContentAdapter(Context context, List<CardModel> data, FragmentActivity activity,int screenWidth) {
        this.context = context;
        this.data = data;
        this.activity = activity;
        mScreenWidth = screenWidth;
    }

    public void setRecyclerViewWidth(int width) {
        this.mScreenWidth  = width;
        // 你可以在这里做进一步的处理，比如计算每个 Item 的宽度
    }


    @Override
    public int getItemViewType(int position) {
         if (position == 0) {
            return TYPE_FIRST;
        }
        return TYPE_NORMAL;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        switch (viewType) {
            case TYPE_FIRST:
                View view1 = inflater.inflate(R.layout.item_one_layout, parent, false);
                return new ViewHolder1(view1);
            case TYPE_NORMAL:
                View view = inflater.inflate(R.layout.itme_pic_vid, parent, false);
                return new ViewHolder2(view);
            default:
                throw new IllegalArgumentException("Unknown view type");
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        // 绑定数据时注意位置的偏移
        if (position == 0) {
            // 绑定 TYPE_FIRST 数据
            bindFirstViewHolder((ViewHolder1) holder, position);
        } else {
            // 由于 TYPE_FIRST 占用了 position 0，正常的数据从 position 1 开始
            int dataPosition = position - 1; // 减去 1 来映射到 data 数组的正确位置
            bindNormalViewHolder((ViewHolder2) holder, dataPosition);
        }
    }


    private void bindNormalViewHolder(ViewHolder2 holder, int position) {
        CardModel item = data.get(position);

        holder.nameTv.setText(item.getTitle());
        holder.woksDes.setText(item.getDescription());

        if (item.getCourse_info().getTag_lv1_id() == 1) {
            holder.tvPositionStatus.setText("私教");
        } else if (item.getCourse_info().getTag_lv1_id() == 2) {
            holder.tvPositionStatus.setText("团课");
        } else if (item.getCourse_info().getTag_lv1_id() == 3) {
            holder.tvPositionStatus.setText("陪练");
        } else if (item.getCourse_info().getTag_lv1_id() == 4) {
            holder.tvPositionStatus.setText("直播");
        }

        holder.loveTv.setOnClickListener(v -> {
            Map<String, Object> jsonParams = new HashMap<>();
            jsonParams.put("studio_id", item.getId());
            String paramsDate = gson.toJson(jsonParams);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
            OkGo.<LzyResponse<FollowModel>>post(Urls.FOLLOW).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<FollowModel>>() {
                @Override
                public void onSuccess(Response<LzyResponse<FollowModel>> response) {
                    FollowModel.FollowInfoBean followModel = response.body().data.getFollow_info();
                    if (followModel != null) {
                        if (followModel.getState() == 1) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                holder.loveTv.setBackground(context.getDrawable(R.drawable.love_icon));
                            }
                            holder.tvLoveNum.setText(String.valueOf(item.getFollow_num() + 1));
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                holder.loveTv.setBackground(context.getDrawable(R.drawable.love_gray_icon));
                            }
                            holder.tvLoveNum.setText(String.valueOf(Integer.parseInt(holder.tvLoveNum.getText().toString().trim()) - 1));
                        }
                    }
                }

                @Override
                public void onError(Response<LzyResponse<FollowModel>> response) {
                    super.onError(response);
                    Toast.makeText(context, "点赞失败", Toast.LENGTH_SHORT).show();
                }
            });
        });

        if (item.getFollow() == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                holder.loveTv.setBackground(context.getDrawable(R.drawable.love_icon));
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                holder.loveTv.setBackground(context.getDrawable(R.drawable.love_gray_icon));
            }
        }

        holder.tvLoveNum.setText(item.getFollow_num() != null ? String.valueOf(item.getFollow_num()) : "0");

        switch (item.getCourse_info().getState()) {
            case 0:
                holder.kcState.setText("未开课");
                break;
            case 1:
                holder.kcState.setText("售卖中");
                break;
            case 2:
                holder.kcState.setText("已满员");
                break;
            case 3:
                holder.kcState.setText("上课中");
                break;
            case 4:
                holder.kcState.setText("已下课");
                break;
        }

        holder.kcV.setText("1 v " + item.getCourse_info().getMax_quantity());
        holder.kcPrice.setText("￥" + item.getCourse_info().getPrice() / 100 + "/节");

        if (!item.getMedia_list().isEmpty()) {
            if (item.getMedia_list().get(0).getMedia_type().equals("Movies")) {
                holder.playView.setVisibility(View.VISIBLE);
                holder.cardImage.setVisibility(View.GONE);

                SimpleExoPlayer mPlayer = new SimpleExoPlayer.Builder(context).build();
                holder.playView.setPlayer(mPlayer);
                MediaItem mediaItem = MediaItem.fromUri(item.getMedia_list().get(0).getMedia_url());
                mPlayer.setMediaItem(mediaItem);
                mPlayer.prepare();
                mPlayer.play();
            } else {
                holder.playView.setVisibility(View.GONE);
                holder.cardImage.setVisibility(View.VISIBLE);
                holder.cardImage.setImageResource(R.drawable.default_image);
                int imageHeight = item.getMedia_list().get(0).getHeight();
                int imageWidth = item.getMedia_list().get(0).getWidth();
                int newHeight = (int) (mScreenWidth/3.0 * (float) imageHeight / (float) imageWidth);
                ViewGroup.LayoutParams layoutParams = holder.cardImage.getLayoutParams();
                                layoutParams.height = newHeight;
                                holder.cardImage.setLayoutParams(layoutParams);
                Glide.with(context)
                        .load(item.getMedia_list().get(0).getMedia_url())
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))
                        .into(holder.cardImage);
            }
        }


        holder.itemView.setOnClickListener(v -> {
            // 处理点击事件
            if (!LoginDialogShowUtil.dialogShow(context)) {
                return;
            }
            LoginWorkDialogHelper loginWorkDialogHelper = new LoginWorkDialogHelper(v.getContext(), data.get(position).getId());
            loginWorkDialogHelper.show();
        });
    }


    private void bindFirstViewHolder(ViewHolder1 holder, int position) {
        if (CashUtil.getInstance().getWoksState() == 0) {
            holder.workHouse.setText("创建工作室");
            Drawable drawable = context.getResources().getDrawable(R.mipmap.add_work_icon);
            holder.workHouse.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            holder.workHouse.setOnClickListener(v -> {
                if (!LoginDialogShowUtil.dialogShow(context)) {
                    return;
                }
                WorkDialogHelper workDialogHelper = new WorkDialogHelper(context, activity, "create");
                workDialogHelper.show();
            });
        } else {
            holder.workHouse.setText("进入我的工作室");
            Drawable drawable = context.getResources().getDrawable(R.mipmap.my_work_icon);
            holder.workHouse.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            holder.workHouse.setOnClickListener(v -> {
                WorkDialogHelper workDialogHelper = new WorkDialogHelper(context, activity, "login");
                workDialogHelper.show();
            });
        }
    }

    @Override
    public int getItemCount() {
        return data.size() + 1;
    }

    public static class ViewHolder1 extends RecyclerView.ViewHolder {
        TextView workHouse;

        public ViewHolder1(View itemView) {
            super(itemView);
            workHouse = itemView.findViewById(R.id.one_layout);
        }
    }

    public static class ViewHolder2 extends RecyclerView.ViewHolder {
        ImageView cardImage;
        PlayerView playView;
        TextView nameTv, woksDes, tvPositionStatus, loveTv, tvLoveNum, kcState, kcV, kcPrice;

        public ViewHolder2(View itemView) {
            super(itemView);
            cardImage = itemView.findViewById(R.id.card_image);
            playView = itemView.findViewById(R.id.play_view);
            nameTv = itemView.findViewById(R.id.name_tv);
            woksDes = itemView.findViewById(R.id.woks_des);
            tvPositionStatus = itemView.findViewById(R.id.tv_position_status);
            loveTv = itemView.findViewById(R.id.love_tv);
            tvLoveNum = itemView.findViewById(R.id.tv_love_num);
            kcState = itemView.findViewById(R.id.kc_state);
            kcV = itemView.findViewById(R.id.kc_v);
            kcPrice = itemView.findViewById(R.id.kc_price);
        }
    }
    }

